//
//  WMEContentViewController.m
//  everyDay_duiTang
//
//  Created by 恩叔 on 16/2/20.
//  Copyright © 2016年 enshu. All rights reserved.
//

#import "WMEContentViewController.h"
#import "WMELayout.h"
#import "WMEAlbumHeadView.h"
#import <AFNetworking.h>
#import "WMEFirstPageModel.h"
#import "WMEFirstPageCollectionViewCell.h"
#import "WMEFirstPageInformationVC.h"
#import "WMEUserViewController.h"
#import <MJRefresh.h>
#pragma mark - 在专辑封面点击 跳转到的专辑详情页 瀑布流
@interface WMEContentViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, WMELayoutItemHeightDelegate,UICollectionViewDelegateFlowLayout, userPushDelegate, pushAlbumDelegate, pushYongHuDelegate>
@property (nonatomic, retain)UICollectionView *collectionView;
@property (nonatomic, retain)NSMutableArray *dataArr;
@property (nonatomic, copy)NSString *url_str;//网络请求的网址
@property (nonatomic, assign)NSInteger count;//给data数组中添加 数据 的个数
@property (nonatomic, retain)NSNumber *next_start;//实际能请求的 数据 个数
@property (nonatomic, retain)NSNumber *maxCount;//数据的 总个数
@property (nonatomic, retain)NSNumber *more;//更多的个数
@property (nonatomic, retain)NSNumber *total;//总个数
@end



@implementation WMEContentViewController
- (void)dealloc
{
    [_collectionView release];
    [_dataArr release];
    [_url_str release];
    [_next_start release];
    [_maxCount release];
    [_more release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = _albumDic[@"name"];

    [self createView];
    [self data];

}
- (void)createView
{
    //自定义layout
    WMELayout *layout = [[WMELayout alloc] init];
    //layout的count为2 两列
    layout.columCount = 2;
    //layout 的 列间距
    layout.columSparce = 10;
    //layout 的 行间距
    layout.rowSparce = 10;
    //layout的边距
    layout.edgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    
    
    //初始化 collection
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT -64) collectionViewLayout:layout];
    //    [layout release];
    //设置collection的背景颜色
    _collectionView.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
    //签协议
    layout.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    
    [self.view addSubview:_collectionView];
    _collectionView.contentInset = UIEdgeInsetsMake(150, 0, 0, 0);
    WMEAlbumHeadView *headView = [[WMEAlbumHeadView alloc] initWithFrame:CGRectMake(0, -150, WIDTH, 150)];
    headView.dic = _albumDic;
    headView.delegate = self;
    [self.collectionView addSubview:headView];
    [headView release];
    //把collection添加进视图
    //未测试
#warning 首页的collectionView 我不会使用 masonry  有 bug 待研究
    //    __block __typeof(&*self)ws = self;
    //    [_collection mas_makeConstraints:^(MASConstraintMaker *make) {
    ////        make.edges.equalTo(ws.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    //        make.left.equalTo(ws.view).with.offset(0);
    //        make.right.equalTo(ws.view).with.offset(0);
    //        make.top.equalTo(ws.view).with.offset(0);
    //        make.bottom.equalTo(ws.view).with.offset(0);
    //    }];
//    [_collectionView registerClass:[WMEAlbumHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"albumHeadView"];
    
    [layout release];
    [_collectionView release];
}

- (void)data
{
    NSString *str = @"http://www.duitang.com/napi/blog/list/by_album/?__dtac=%257B%2522_r%2522%253A%2520%2522661071%2522%257D&album_id=77153908&app_code=gandalf&app_version=5.9%20rv%3A150681&device_name=Unknown%20iPhone&device_platform=iPhone7%2C2&include_fields=sender%2Cfavroite_count%2Calbum%2Cicon_url%2Creply_count%2Clike_count&limit=0&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2&screen_height=667&screen_width=375&sender_id=0&start=0&user_id=8455538";
    self.url_str = [[str stringByReplacingOccurrencesOfString:@"album_id=77153908" withString:[NSString stringWithFormat:@"album_id=%@", _albumDic[@"id"]]] stringByReplacingOccurrencesOfString:@"user_id=8455538" withString:[NSString stringWithFormat:@"user_id=%@", _albumDic[@"user"][@"id"]]];
 
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
    [data GET:_url_str parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//      NSLog(@"%@", responseObject);
        NSArray *arr = responseObject[@"data"][@"object_list"];
        self.next_start = responseObject[@"data"][@"next_start"];
        self.total = responseObject[@"data"][@"total"];
        _count += 24;
        self.dataArr = [WMEFirstPageModel modelHandlerWithArray:arr];
        if (_dataArr.count == 0) {
            UILabel *kbLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64)];
            kbLabel.text = @"此专辑为空";
            kbLabel.textAlignment = NSTextAlignmentCenter;
            [self.view addSubview:kbLabel];
            [kbLabel release];
        }else{
            //下拉刷新
            [self refreshFunction];
            //上拉加载
            [self loadingFunction];
        }
        [_collectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];

}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //注册重用池 为cell
    [collectionView registerClass:[WMEFirstPageCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    //创建cell
    WMEFirstPageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    //创建model
    if (_dataArr.count != 0) {
        WMEFirstPageModel *m = _dataArr[indexPath.item];
        //把 model 传递给 cell
        cell.model = m;
        cell.delegate = self;
        cell.albumDelegate = self;
    }
    return cell;
}

- (CGFloat)layout:(WMELayout *)layout heightForItemAtIndexPath:(NSIndexPath *)indexPath width:(CGFloat)width
{
    //计算图片的高度
    //tw/th = iw/ih
    if (_dataArr.count != 0) {
        WMEFirstPageModel *m = _dataArr[indexPath.item];
        //图片高度
        CGFloat imgH = width * m.height.doubleValue / m.width.doubleValue;
        //文字高度
        //    NSDictionary *dic = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};
        //    // 预设尺寸 文本最大不超过这个尺寸
        //    // 根据设置的宽度计算高度(宽度和label保持一致)
        //    CGSize size = CGSizeMake((414 - 30) /2, 1000);
        //    // 根据文本 计算出一个CGRect
        //    // 参数1: 尺寸范围
        //    // 参数2: 文本属性
        //    // 参数3: 按照什么方式获取rect
        //    // 参数4: nil
        //    CGRect rect = [m.msg boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        //    CGFloat h3 = rect.size.height;
        
        //文本高度
        CGFloat textHeight = [WMEFirstPageCollectionViewCell heightWithText:m.msg];
        //判断文本框 高度是否 超过 15.51 * 6 的 高度(6行的高度)
        if (textHeight >= 15.51 * 6) {
            //设置最大文本框行数 为 6行;
            textHeight = 15.51 * 6;
        }
        //    NSLog(@"%@      ======     %f  ~~~~ %f", m.msg, imgH, textHeight);
        // 每个cell的高度 由 图片高度 和 文本高度  + 其他控件高度(80)
        return imgH + textHeight + 80;
    }
    return 0;
}

#pragma mark -点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    //    NSLog(@"indexPath:%ld", (long)indexPath.row);
    //创建 对象
    WMEFirstPageInformationVC *information = [[WMEFirstPageInformationVC alloc] init];
    WMEFirstPageModel *m = _dataArr[indexPath.item];
    //把ID 传递给 下一页 的 接口
    information.jiekou = m.ID.stringValue;
    [self.navigationController pushViewController:information animated:YES];
    [information release];
}
#pragma mark -刷新
- (void)refreshFunction
{
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.dataArr removeAllObjects];
        [self data];
        [self.collectionView.mj_header endRefreshing];
    }];
}
#pragma maek - 加载
- (void)loadingFunction
{
    //数据不为空的时候 加载
    if(_dataArr.count != 0)
    {
        self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            NSString *url = [[_url_str stringByReplacingOccurrencesOfString:@"start=0" withString:[NSString stringWithFormat:@"start=%@", _next_start]] stringByReplacingOccurrencesOfString:@"limit=0" withString:[NSString stringWithFormat:@"limit=%@", _total]];
            //AFN网络请求
            AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
            [data GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                nil;
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                //        NSLog(@"%@", responseObject);
                NSArray *arr = responseObject[@"data"][@"object_list"];
                self.next_start = responseObject[@"data"][@"next_start"];
                // 把新请求来的数据 添加进 dataArr 数组
                NSArray *temp = [WMEFirstPageModel modelHandlerWithArray:arr];
                [_dataArr addObjectsFromArray:temp];
                [_collectionView reloadData];
                if (_next_start.integerValue >_total.integerValue) {
                    [_collectionView.mj_footer endRefreshingWithNoMoreData];
                }else{
                    [_collectionView.mj_footer endRefreshing];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                nil;
            }];
        }];
    }
}

#pragma mark - push用户界面(协议方法)
- (void)pushYongHu:(NSString *)str
{
    NSString *userTemp = @"http://www.duitang.com/napi/people/profile/?__dtac=%257B%2522_r%2522%253A%2520%2522998121%2522%257D&_ts=1452865118.002704&app_code=gandalf&app_version=5.8%20rv%3A149591&device_name=iPhone%205&device_platform=iPhone5%2C2&include_fields=relationship%2Cbind_status%2Cinterests%2Cidentity%2Ccity%2Ccitycode%2Cgender%2Cbirthday%2Crecommend_info%2Cclub_count&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2&screen_height=568&screen_width=320&user_id=11200118";
    NSString *userStr = [userTemp stringByReplacingOccurrencesOfString:@"11200118" withString:str];
    //AFN网络请求
    AFHTTPSessionManager *userData = [AFHTTPSessionManager manager];
    [userData GET:userStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"%@", responseObject);
        NSMutableDictionary *dic = responseObject[@"data"];
        WMEUserViewController *userVC = [[WMEUserViewController alloc] init];
        UINavigationController *userNavi = [[UINavigationController alloc] initWithRootViewController:userVC];
        userVC.userId = str;
        userVC.userDic = dic;
        [self presentViewController:userNavi animated:YES completion:^{
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
    
    
}

#pragma mark - push专辑页 (协议方法)
- (void)pushAlbum:(NSString *)str maxCount:(NSNumber *)count
{
    //AFN网络请求
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
    NSString *temp = @"http://www.duitang.com/napi/album/detail/?__dtac=%257B%2522_r%2522%253A%2520%2522616818%2522%257D&album_id=77153908&app_code=gandalf&app_version=5.9%20rv%3A150681&device_name=Unknown%20iPhone&device_platform=iPhone7%2C2&include_fields=id%2Cname%2Cdesc%2Cuser%2Clike_count%2Clike_id%2Ccount%2Ccovers%2Cmanagers%2Cmembers%2Cmember_count%2Ccategory%2Cshare_links_2&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2&screen_height=667&screen_width=375&user_id=0";
    NSString *urlStr = [temp stringByReplacingOccurrencesOfString:@"album_id=77153908" withString:[NSString stringWithFormat:@"album_id=%@",str]];
    [data GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"%@", responseObject);
        NSMutableDictionary *dic = responseObject[@"data"];
        WMEContentViewController *contentView = [[WMEContentViewController alloc] init];
        contentView.albumDic = dic;
        [self.navigationController pushViewController:contentView animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)userPushAction:(NSString *)str userDic:(NSDictionary *)dictionary
{
    WMEUserViewController *userVC = [[WMEUserViewController alloc] init];
    UINavigationController *userNavi = [[UINavigationController alloc] initWithRootViewController:userVC];
    userVC.userId = str;
    userVC.userDic = dictionary;
    [self presentViewController:userNavi animated:YES completion:^{
    }];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
